import json
from flask import jsonify, request
from . import cmdb
from . import tasks
from app.app_1_0.cmdb.models import User22, Area, db
from app import csrf, cache

@csrf.exempt
@cmdb.route('/create', methods=['GET', 'POST'])
def create():
    if request.method == "POST":
        data = request.get_json()
        users = User22(**data)
        db.session.add(users)
        db.session.commit()
        return jsonify({"status": 0, "message": "ok"})


@cmdb.route('/del', methods=['GET'])
def deleting():
    user_id = request.args.get('id')
    result = User22.query.filter_by(id=user_id).first()
    db.session.delete(result)
    db.session.commit()
    print(result)
    return jsonify({"status": 0})


@csrf.exempt
@cmdb.route('/update', methods=['GET', 'POST'])
def update():
    try:
        params = request.get_json()
        user_id = request.args.get('id')
        result = User22.query.filter(User22.id == user_id)
        # result = User.query.get(user_id)                      # get的用法，主键参数
        result.update(params)
        db.session.commit()
        return jsonify({'status': 0, "result": "ok"})
    except Exception as e:
        return jsonify({'status': -1})


@cmdb.route('/query', methods=['GET', 'POST'])
@cache.cached(timeout=60)
def query():
    user_name = request.args.get('name')
    area_id = User22.query.filter_by(name=user_name).first().area_id
    area_name = Area.query.filter_by(id=area_id).first().name

    usersssss = Area.query.filter_by(name='浙江').first().users
    for u in usersssss:
        print(u.name, u.mobile)

    print("testing cache")
    user_list = User22.query.all()
    area_list = Area.query.all()
    users = [user.to_dict() for user in user_list]
    areas = [area.to_dict() for area in area_list]
    return jsonify({'status': 0, "user_list": users, 'area_list': areas})


@cmdb.route('/filter', methods=['GET'])
def filter():
    user_id = request.args.get('id')
    user_id = json.loads(user_id)
    users = User22.query.filter(User22.id.in_(user_id))
    if not users:
        return jsonify({'status': -1})
    else:
        result = [user.to_dict() for user in users]
    return jsonify({'status': 0, "user_list": result})


@cmdb.route('/send', methods=['GET'])
def sending_mail():
    print('send_mail')
    tasks.send_msg.delay()
    print("ok")
    return jsonify({'status': 0})


@cmdb.route('/', methods=['GET'])
def test():
    result = to_dict()
    print(result)
    return jsonify({'result':0})
